import { defineComponent } from 'vue';
import { List } from 'vant';
import { dateFormatter } from '@/utils';

export default defineComponent({
  name: 'MTable',
  props: {
    renderList: {
      required: true
    },
    requestApi: {},
    searchItems: {},
    list: {}
  },
  emits: ['viewDetail'],
  setup(props: any, { emit, expose }) {
    const list = ref([]) as any;
    const searchResult = ref();
    const loadParams = reactive({
      loading: false,
      total: 0,
      finished: false
    });
    const searchItem = reactive({ page: 1, pageSize: 15 }) as AnyObject;
    const loadMore = () => {
      console.log(1);
      console.log(props.list);

      if (!props.requestApi) {
        list.value = props.list;
        loadParams.finished = true;
        return;
      }
      loadParams.loading = true;
      props.requestApi?.(searchItem).then((res: AnyObject) => {
        searchResult.value = res;
        const listData = res.data ? res.data.list : res.datas;
        const total = res.data?.total || res.total || 0;
        list.value.push(...listData);
        searchItem.page++;
        if (list.value.length >= total) {
          loadParams.finished = true;
        }
        loadParams.loading = false;
      });
    };
    const search = () => {
      searchItem.month && (searchItem.month = dateFormatter(searchItem.month));
      searchItem.year && (searchItem.year = dateFormatter(searchItem.year));
      searchItem.dateTime &&
        (searchItem.dateTime = dateFormatter(searchItem.dateTime));
      list.value = [];
      searchItem.page = 1;
      loadParams.finished = false;
      loadMore();
    };
    watch(
      () => props.searchItems,
      (val: AnyObject) => {
        Object.assign(searchItem, val);
        console.log('cbcvbvvvvvvvvvvv');
        if (props.requestApi) {
          search();
        } else {
          loadParams.finished = true;
          // list.value = props.list;
        }
      },
      {
        immediate: true,
        deep: true
      }
    );

    expose({ search, searchResult });
    return () => (
      <div class="data_wrap">
        <p class="title flex-between">
          {props.renderList.map((_item: AnyObject) => (
            <span>{_item.title}</span>
          ))}
        </p>
        <List
          v-model:loading={loadParams.loading}
          finished={loadParams.finished}
          finished-text="没有更多了"
          onLoad={loadMore}
        >
          {(props.list || list.value)?.map((_item: AnyObject) => (
            <div
              class="list_item flex-between"
              onClick={() => emit('viewDetail', _item)}
            >
              {props.renderList.map((_item2: AnyObject) => (
                <span>
                  {_item2.render?.(_item[_item2.key]) || _item[_item2.key]}
                </span>
              ))}
            </div>
          ))}
        </List>
      </div>
    );
  }
});
